<?php
require_once("Artist.php");
/**
 * Class related to data entered by the user
 * 
 * @author Magnus Stoveland <mstoveland@gmail.com>
 *  
 */
class Input
{
    /**
     * Split string to an array
     *
     * @param string $string
     * @param string $separator
     * @return array exploded string
     */
    function split_string($string, $separator = ", ") {
        $string_array = explode($separator, $string);
        foreach($string_array as $artist) {
            $userMusic = new UserMusic();
            $userMusic->artist = $artist;
            $userMusic->weight = 100;
            $output[] = $userMusic;
        }
        return $output;
    }
    
    /**
     * Desc 
     * 
     * @param string $tag
     * @return array with UserMusic-objects
     */
    function getTagTopArtists($tag) {
        $file = "./cache/tag/".urlencode($tag).".xml";
        if (@fopen($file, "r")) {
            $sxml = simplexml_load_file($file);
        } else {
            $xml = file_get_contents("http://ws.audioscrobbler.com/2.0/?method=tag.gettopartists&tag=".urlencode($tag)."&api_key=519681edb551a3b5177bb67352e16136");
            $fp = @fopen($file, "w");
            if($fp) {
               $result = fwrite($fp, $xml);
            fclose($fp);
            }
            $sxml = new SimpleXMLElement($xml);
        }
        try {
            $sxml = $sxml->topartists;
    		foreach($sxml->artist as $obj) {
                $artist = new Artist();
                $artist->name = $obj->name;
                $artist->weight = $obj['rank']; // Empty from the XML for now..
                $output[] = $artist;
    		}
        } catch(Exception $e) {
            
        }
		return $output;
    }
    
    /**
     * Desc 
     * 
     * @param string $username
     * @return array with UserMusic-objects
     */
    function getUserTopArtists($username) {
        $file = "./cache/username/".urlencode($username).".xml";
        if (@fopen($file, "r")) {
            $sxml = simplexml_load_file($file);
        } else {
            $xml = file_get_contents("http://ws.audioscrobbler.com/2.0/?method=user.gettopartists&user=".urlencode($username)."&api_key=519681edb551a3b5177bb67352e16136");
            $fp = @fopen($file, "w");
            if($fp) {
               $result = fwrite($fp, utf8_encode($xml));
            fclose($fp);
            }
            $sxml = new SimpleXMLElement($xml);
        }
        try {
            $sxml = $sxml->topartists;
            foreach($sxml->artist as $obj) {
                $artist = new Artist();
                $artist->name = $obj->name;
                $artist->weight = $obj['rank']; // Empty from the XML for now..
                //Info::dump($artist);die;
                $output[] = $artist;
            }
        } catch(Exception $e) {
            
        }
        return $output;
    }
}
?>